<template>
  <div class="search">
    <!-- 三级分类导航 -->
    <TypeNav />
    <!-- 内容区开始 -->
    <div class="search-wrap">
      <!-- 面包屑 -->
      <div class="search-crumbs-nav" @click="delTagFn">
        <div class="first">搜索结果</div>
        &nbsp;&nbsp;&gt;&nbsp;&nbsp;
        <!-- keyword 对应的面包屑标签 -->
        <div class="search-crumb" v-show="$route.query.keyword">
          {{ $route.query.keyword }}
          <span @click="delUrlFn('keyword')">×</span>
        </div>
        <!-- 一级菜单对应的面包屑标签 -->
        <div class="search-crumb" v-show="$route.query.categoryName">
          {{ $route.query.categoryName }}
          <span @click="delUrlFn('categoryName')">×</span>
        </div>
        <!-- 品牌对应的面包屑标签 -->
        <div class="search-crumb" v-show="sendData.trademark">
          {{ sendData.trademark.split(':')[1] }}
          <span @click="delTradTagFn('categoryName')">×</span>
        </div>
        <!-- 其他面包屑标签 -->
        <div
          class="search-crumb"
          v-for="prop in sendData.props"
          :key="prop"
          :data-name="prop"
        >
          {{ prop | formatTagText }} <span>×</span>
        </div>
      </div>
      <div v-show="receiveData.goodsList && receiveData.goodsList.length">
        <!-- 导航栏 -->
        <div class="search-logo-nav" @click="addTagFn">
          <!-- 品牌栏 -->
          <div class="nav-row">
            <div class="nav-title">品牌：</div>
            <ul class="nav-content">
              <!-- 遍历生成 品牌栏的数据 -->
              <li
                v-for="tm in receiveData.trademarkList"
                :data-name="'品牌：' + tm.tmName"
                :key="tm.tmId"
                @click="sendData.trademark = `${tm.tmId}:${tm.tmName}`"
              >
                {{ tm.tmName }}
              </li>
            </ul>
          </div>
          <!-- 遍历生成下面的可选参数栏 -->
          <div
            class="nav-row"
            v-for="attr in receiveData.attrsList"
            :key="attr.attrId"
          >
            <div class="nav-title">{{ attr.attrName }}：</div>
            <div class="nav-content">
              <a
                v-for="(attrVal, index) in attr.attrValueList"
                :key="index"
                :data-name="attr.attrId + ':' + attrVal + ':' + attr.attrName"
              >
                {{ attrVal }}</a
              >
            </div>
          </div>
        </div>
        <!-- 排序栏 -->
        <ul class="search-sort" @click="sortFn">
          <li data-type="1" :class="{ active: cOrder[0] === '1' }">
            综合
            <span
              v-show="cOrder[0] === '1'"
              class="iconfont"
              :class="
                cOrder[1] === 'asc'
                  ? 'icon-jiantoushangsheng'
                  : 'icon-jiantouxiajiang'
              "
            ></span>
          </li>
          <li data-type="2" :class="{ active: cOrder[0] === '2' }">
            价格
            <span
              v-show="cOrder[0] === '2'"
              class="iconfont"
              :class="
                cOrder[1] === 'asc'
                  ? 'icon-jiantoushangsheng'
                  : 'icon-jiantouxiajiang'
              "
            ></span>
          </li>
        </ul>
        <!-- 商品列表 -->
        <ul class="goods-list">
          <li v-for="goodsInfo in receiveData.goodsList" :key="goodsInfo.id">
            <div class="goods-img-wrap">
              <router-link :to="`/detail/${goodsInfo.id}`"
                ><img :src="goodsInfo.defaultImg" alt="图片"
              /></router-link>
            </div>
            <p class="goods-price">¥ {{ goodsInfo.price }}</p>
            <p class="goods-info">
              <a v-html="goodsInfo.title"></a>
            </p>
            <p class="goods-evaluate"><span>2000+</span>条评价</p>
            <p class="goods-operation">
              <a><i class="car"></i>加入购物车</a>
              <a><i class="heart"></i>收藏</a>
            </p>
          </li>
        </ul>
        <!-- 自定义分页 -->
        <ZPagination
          :page-size="pageSize"
          :total="receiveData.total"
          :current-page="pageNo"
          @prev-click="pageChangeHandle"
          @next-click="pageChangeHandle"
          @current-change="handleCurrentChange"
        />
        <!-- eleme上的分页 -->
        <!-- <el-pagination
          class="pagination"
          background
          layout="prev, pager, next,sizes,total"
          :page-size="sendData.pageSize"
          :total="receiveData.total"
          :current-page="sendData.pageNo"
          :page-sizes="[5, 10, 15, 20]"
          @prev-click="sendData.pageNo--"
          @next-click="sendData.pageNo++"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        >
        </el-pagination> -->
      </div>
      <!-- 空数据展示 -->
      <div
        v-show="receiveData.goodsList && !receiveData.goodsList.length"
        class="empty"
      >
        <img src="./imgs/error_06.png" alt="" />
        <h1>抱歉，搜索结果为空！</h1>
      </div>
    </div>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'

import { reqPostSearchList } from '@/api/searchAPI'
import TypeNav from '@/components/TypeNav'
import ZPagination from '@/components/Pagination'
export default {
  name: 'ZSearch',
  components: {
    TypeNav,
    ZPagination,
  },
  data() {
    return {
      //请求返回的数据
      receiveData: {},
      //发送请求携带的部分参数
      pageNo: 1,
      pageSize: 5,
      sendData: {
        order: '1:desc',
        props: [],
        trademark: '',
      },
    }
  },

  methods: {
    // 删除路径中的keyword和category的方法
    delUrlFn(attr) {
      let newQuery = JSON.parse(JSON.stringify(this.$route.query))
      Object.keys(newQuery).forEach((key) => {
        if (attr === 'keyword') {
          delete newQuery[attr]
        } else if (key.includes(attr.slice(0, 4))) {
          delete newQuery[key]
        }
      })
      this.pageNo = 1
      this.$router.replace({ query: newQuery }) //再把新的替换了
    },
    // 添加面包屑的方法
    addTagFn(e) {
      this.pageNo = 1
      const { name } = e.target.dataset
      const { props } = this.sendData
      if (props.includes(name) || !name) return
      if (!name.includes('品牌')) props.push(name)
    },
    // 删除品牌面包屑
    delTradTagFn() {
      this.sendData.trademark = ''
    },
    // 删除面包屑方法
    delTagFn(e) {
      this.pageNo = 1
      let { props } = this.sendData
      const { name } = e.target.parentNode.dataset
      if (!name) return
      this.sendData.props = props.filter((prop) => prop != name)
      name.includes('品牌') && (this.sendData.trademark = '')
    },
    // 排序的方法
    sortFn(e) {
      let target = e.target
      if (e.target.tagName == 'SPAN') target = target.parentNode
      const { type } = target.dataset
      if (!type) return
      let [newType, flag] = this.cOrder
      if (newType == type) {
        flag = flag == 'asc' ? 'desc' : 'asc'
      } else {
        flag = 'desc'
      }
      this.sendData.order = type + ':' + flag
    },
    // 分页的方法------------------------开始
    handleSizeChange(size) {
      this.pageSize = size
      this.getSearchListFn()
    },
    pageChangeHandle: debounce(
      function (num) {
        this.pageNo = num
        this.getSearchListFn()
      },
      300,
      { maxWait: 3000 }
    ),
    handleCurrentChange(page) {
      this.pageNo = page
      this.getSearchListFn()
    },
    // 分页的方法------------------------结束

    // 发送请求的方法
    async getSearchListFn(arg) {
      let res
      if (arg) {
        res = await reqPostSearchList({
          ...this.sendData,
          ...this.$route.query,
          pageNo: 1,
          pageSize: this.pageSize,
        })
      } else {
        res = await reqPostSearchList({
          ...this.sendData,
          ...this.$route.query,
          pageNo: this.pageNo,
          pageSize: this.pageSize,
        })
      }

      this.receiveData = res
    },
  },
  filters: {
    // 格式化面包屑的内容
    formatTagText(text) {
      if (text.includes('品牌')) return text
      text = text.split(':').reverse()
      text.pop()
      return text.join('：')
    },
  },
  computed: {
    cOrder() {
      return this.sendData.order.split(':')
    },
  },
  watch: {
    // 路由发生变化请求数据
    $route: {
      deep: true,
      immediate: true,
      handler() {
        this.getSearchListFn()
      },
    },
    // 面包屑发生变化请求数据
    sendData: {
      deep: true,
      handler() {
        this.pageNo = 1
        this.getSearchListFn(true)
      },
    },
  },
}
</script>

<style lang="less" scoped>
.empty {
  text-align: center;
  h1 {
    padding-left: 40px;
    font-size: 18px;
    margin: 10px 0;
    color: #bbb;
  }
}
.pagination {
  text-align: center;
  margin: 20px 0;
}
.search-wrap {
  width: 1260px;
  margin: 0 auto;
}
.search-crumbs-nav {
  padding: 0 0 0 50px;
  display: flex;
  align-items: center;
  line-height: 50px;
  flex-wrap: wrap;
}
.first {
  // padding: 0 5px 0 5px;
  font-size: 18px;
  color: #666;
  font-weight: bold;
}
.search-crumb {
  height: 20px;
  line-height: 20px;
  padding: 0 0 0 5px;
  background-color: #f3f3f3;
  border: 1px solid #ccc;
  margin: 0 5px;
  cursor: pointer;
  span {
    margin-left: 5px;
    font-size: 16px;
    padding-right: 5px;
    padding-left: 5px;
    color: #e1251b;
  }
  &:hover {
    border-color: #e1251b;
  }
  &:hover span {
    color: #fff;
    background-color: #e1251b;
  }
}
.search-logo-nav {
  padding-left: 30px;
  border-right: 1px solid #f3f3f3;
}
.nav-row {
  display: flex;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  margin-top: -1px;
}
.nav-title {
  box-sizing: border-box;
  background-color: #f3f3f3;
  width: 90px;
  line-height: 45px;
  font-size: 12px;
  font-weight: bold;
  color: #666;
  padding: 0 0 0 10px;
  text-align: right;
}
.nav-content {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  padding: 15px;
  box-sizing: border-box;
  li {
    height: 46px;
    line-height: 46px;
    text-align: center;
    font-size: 14px;
    width: 100px;
    border: 1px solid #eee;
    margin: -1px -1px 0 0;
    cursor: pointer;
    color: #005aa0;
    &:hover {
      position: relative;
      z-index: 5;
      border-color: #e1251b;
      color: #e1251b;
    }
  }
  a {
    margin: 0 15px;
    cursor: pointer;
    &:hover {
      color: #e1251b;
    }
  }
}
.search-sort {
  display: flex;
  margin: 10px 0;
  margin-left: 30px;
  background-color: #fbfbfb;
  border: 1px solid #eee;
  li {
    width: 50px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 12px;
    color: #666;
    cursor: pointer;
    &.active {
      background-color: #e1251b;
      color: #fff;
    }
  }
}
.goods-list {
  display: flex;
  flex-wrap: wrap;
  padding-left: 30px;
  li {
    position: relative;
    margin-top: 10px;
    width: 246px;
    height: 410px;
    box-sizing: border-box;
    border: 1px solid transparent;
    transition: all 0.2s linear;

    p {
      padding: 0 10px;
      // margin: 10px 0;
    }
    &:hover {
      box-shadow: 0 0 2px rgba(0, 0, 0, 0.2);
      border-color: #eee;
    }
  }
}
.goods-img-wrap {
  // border: 1px solid #666;
  height: 255px;
  line-height: 255px;
  width: 230px;
  margin: 0 auto 10px;
  overflow: hidden;
  text-align: center;
  img {
    width: 100%;
    // height: 100%;
    vertical-align: middle;
  }
}
.goods-price {
  color: #c81623;
  font-weight: bold;
  font-size: 18px;
}
.goods-info {
  line-height: 20px;
  margin: 5px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
.goods-evaluate {
  color: #a7a7a7;
  span {
    color: #005aa0;
    font-weight: bold;
  }
}
.goods-operation {
  margin: 10px 0 18px;
  position: absolute;
  bottom: 0;
  a {
    display: inline-block;
    box-sizing: border-box;
    width: 113px;
    height: 27px;
    line-height: 27px;
    border: 1px solid #ccc;
    text-align: center;
    cursor: pointer;
    margin-right: -1px;
    &:hover {
      position: relative;
      z-index: 3;
      border-color: #c81623;
      color: #c81623;
      i.heart {
        background-position: 0 -438px;
      }
    }
    i {
      display: inline-block;
      width: 18px;
      height: 18px;
      background-image: url('./imgs/search.ele.png');
      vertical-align: middle;
      margin-right: 4px;
      transition: all 0.2s linear;
    }
  }
}
.heart {
  background-position: 0 -415px;
}
.car {
  background-position: 0 -273px;
}
</style>
